import base64
import json
import re

from django.core.cache import caches
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.utils import timezone

from polls.captcha import Captcha
from polls.models import Subject, Teacher, User
from polls.util import make_sha256_digest, gen_verify_code, gen_mobile_code, send_mobile_code


TEL_PATTERN = re.compile(r'1[3-9]\d{9}')

def index(request):
    context = '<h1>你不是爱我，你只是爱我的弟弟</h1>\n' \
              '<h1>你喜欢大海，我爱过你</h1>'
    return HttpResponse(context)


def get_mobile_code(request):
    '''发送短信验证码'''
    tel = request.GET.get('tel')
    if TEL_PATTERN.fullmatch(tel):
        if caches['default'].get(f'voteapp:polls:block:{tel}'):
            data = {'code': 2004, 'msg': '请不要在60秒以内重复发送短信验证码!'}
        else:
            code = gen_mobile_code()
            result = send_mobile_code(tel, code)
            if result['error'] == 0:
                caches['default'].set(f'voteapp:polls:block:{tel}', code, 60)
                caches['default'].set(f'voteapp:polls:valid:{tel}', code, 60000)
                data = {'code':2000, 'msg':'成功!'}
            else:
                data = {'code':2001, 'msg':'失败!'}

    else:
        data = {'code': 2003, 'msg':'手机号码无效!'}
    return JsonResponse(data)


def captcha(request):
    '''生成验证码'''
    code_text = gen_verify_code()
    request.session['code'] = code_text
    image_data = Captcha.instance().generate(code_text)
    return HttpResponse(image_data, content_type='image/png')


def show_subjects(requst):
    '''展示所有学科'''
    querset = Subject.objects.all()
    return render(requst, 'subjects.html', {'subjects': querset})


def login(request):
    '''登录页面'''
    hint = ''
    if request.method == 'GET':

        backurl = request.GET.get('backurl')
        backurl = base64.b64decode(backurl).decode() if backurl else '/'

    else:
        backurl = request.POST.get('backurl', '/')
        print(backurl)

        code_from_user = request.POST.get('captcha', '0')
        code_from_serv = request.session.get('code', '1')

        if code_from_serv.lower() == code_from_user.lower():

            username = request.POST.get('username')
            password = request.POST.get('password')
            print('-----', username, password)
            if username and password:
                print(username, password)
                password = make_sha256_digest(password)
                print('===', password)
                # user = User.objects.filter(username=username).filter(password=password).first()
                user = User.objects.filter(Q(username=username) | Q(tel=username)).filter(password=password).first()

                if user:
                    # 利用timezone不用datatime.now()
                    # delta = timezone.now() - user.last_visit
                    print(timezone.now())
                    print(user.last_visit)

                    # print(delta.days,delta.hour)
                    request.session['userid'] = user.userid
                    request.session['username'] = user.username
                    return redirect(backurl)
                else:
                    hint = '用户名或者密码错误❌'
            else:
                hint = '请提供有效的用户名和密码✔'
        else:
            hint = '宝贝,请输入有效的验证码'
    return render(request, 'login.html', {'hint': hint, 'backurl': backurl})


def logout(request):
    '''退出登录'''
    request.session.flush()
    return redirect('/polls/')

def register(request):
    '''注册页面'''
    if request.method =='GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        context = {
            'hint': ''  ,
            'code':200,
        }
        tel = request.POST.get('tel')
        mobilecode = str(request.POST.get('mobilecode'))
        mob = str(caches['default'].get(f'voteapp:polls:valid:{tel}'))
        username = request.POST.get('username')
        password = make_sha256_digest(request.POST.get('password'))
        print(type(mobilecode),type(mob))
        if mob == mobilecode:
            print(password)
            user = User()
            user.username = username
            user.password = password
            user.tel = tel
            user.save()
            context['hint'] = '注册成功，请返回登录'
        else:
            context['hint'] = '验证码输入不正确。请重新输入'
            context['code'] = 201
    # return JsonResponse(context)
    return render(request, 'register.html',context=context)


def checkName(request):
    data = {
        'status':200,
        'msg':'恭喜你，用户名可用'
    }
    username = request.GET.get('username')
    users = User.objects.filter(username=username)
    print(username,users)

    if users.exists():
        data['msg'] = '该用户名已存在'
        data['status'] = 201

        return JsonResponse(data=data)
    else:
        return JsonResponse(data=data)


def praise_or_bad(request):
    '''
    好评
    :param request: tno
    :return: JsonResponse
    '''

    # 设置只允许Ajax请求
    if not request.is_ajax():


        return render(request,'erro.html')

    if request.session.get('userid') is None:
        result = {'code': 101, 'msg': '请先登录'}
        return JsonResponse(result)
     # request.path可以获取请求的路径
    is_praise = request.path == '/polls/praise/'
    try:
        tno = int(request.GET.get('tno', '0'))
        teacher = Teacher.objects.get(no=tno)
        if is_praise:
            teacher.good_count += 1
        else:
            teacher.bad_count += 1
        teacher.save()
        resullt = {
            'code': 200,
            'msg': '操作成功',
            'count': teacher.good_count if is_praise else teacher.bad_count,

        }
        # MIME 类型  - 响应的内容类型
        # text/html text/xml
        return JsonResponse(resullt)
    except(ValueError, Teacher.DoesNotExist):
        resullt = {
            'code': 101,
            'msg': '操作失败',

        }
        return JsonResponse(resullt)


def show_teacher(request):
    try:
        sno = int(request.GET.get('sno', '0'))
        queryset = Teacher.objects.filter(subject__no=sno)
        name = request.GET.get('name')

        context = {
            'status': 200,
            'teachers': queryset,
            'name': name,
        }
        return render(request, 'teachers.html', context=context)

    except(KeyError, ValueError):
        return redirect('/polls/')
